<template>
  <div class="dashboard-console">
    <!-- 统计卡片行 -->
    <el-row :gutter="16">
      <el-col :span="6" v-for="(card, index) in statisticsCards" :key="index">
        <div class="statistics-card">
          <div class="art-card">
            <div class="card-content">
              <div class="card-title">{{ card.title }}</div>
              <div class="card-value">{{ card.value }}</div>
              <div class="card-footer">
                <span :class="['trend', card.trend > 0 ? 'up' : 'down']">
                  {{ Math.abs(card.trend) }}%
                  <el-icon><CaretTop v-if="card.trend > 0" /><CaretBottom v-else /></el-icon>
                </span>
                <span class="compared">较上周</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表行 -->
    <el-row :gutter="16" class="chart-row">
      <el-col :span="12">
        <div class="art-card">
          <div class="card-header flex justify-between">
            <h3>游客流量趋势</h3>
            <el-date-picker
              v-model="dateChange"
              type="date"
              placeholder="选择时间"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYYMMDD"
              :clearable="false" 
              @change="getHourNumOnTypeByDate"
            />
          </div>
          <div class="chart-content">
            <ArtBarChart
              :data="visitorTrendData"
              :xAxisData="weekDays"
            />
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="art-card">
          <div class="card-header">
            <h3>游客来源分布</h3>
          </div>
          <div class="chart-content">
            <div class="visitor-overview">
              <div class="chart-section">
                <ArtRingChart
                  :data="visitorSourceData"
                  :color="['#4C87F3', '#8BD8FC', '#93F1B4']"
                  :radius="['35%', '45%']"
                  :showLabel="false"
                  :borderRadius="0"
                />
              </div>
              <div class="data-section">
                <div class="source-list">
                  <div v-for="item in visitorSourceDetails" :key="item.title" class="source-item">
                    <div class="source-info">
                      <div class="title-row">
                        <div class="source-title">
                          <span class="dot" :style="{ backgroundColor: item.color }"></span>
                          <span class="title">{{ item.title }}</span>
                        </div>
                        <span class="count">{{ item.count }}</span>
                      </div>
                      <el-progress 
                        :percentage="item.percent" 
                        :color="item.color"
                        :show-text="false"
                        :stroke-width="6"
                      />
                      <div class="trend-info">
                        <span class="percent">占比 {{ item.percent }}%</span>
                        <span class="trend" :class="{ 'positive': item.trend > 0 }">
                          {{ item.trend > 0 ? '+' : '' }}{{ item.trend }}%
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 列表行 -->
    <el-row :gutter="16" class="list-row">
      <el-col :span="12">
        <ArtDataListCard
          title="最新活动"
          :list="activityList"
          :maxCount="5"
          showMoreButton
          @more="handleMoreActivity"
        />
      </el-col>
      <el-col :span="12">
        <ArtDataListCard
          title="反馈处理"
          :list="feedbackList"
          :maxCount="5"
          showMoreButton
          @more="handleMoreFeedback"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, defineAsyncComponent, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { CaretTop, CaretBottom } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  scenicActivityPageActivityUsingPost 
} from '@/api/4a/huodongguanli'
import { 
  scenicComplaintFeedbackGetComplaintFeedbackUsingPost 
} from '@/api/4a/tousuyufankuibiao'
import {
  passengerFlowStatisticsHourNumOnTypeByDateUsingPost
} from '@/api/4a/keliushuju'
import { useDateFormat } from '@vueuse/core'

// 异步导入组件
const ArtBarChart = defineAsyncComponent(() => import('@/components/core/charts/ArtBarChart.vue'))
const ArtRingChart = defineAsyncComponent(() => import('@/components/core/charts/ArtRingChart.vue'))
const ArtDataListCard = defineAsyncComponent(() => import('@/components/core/cards/ArtDataListCard.vue'))

const router = useRouter()

// 统计卡片数据
const statisticsCards = ref([
  { title: '总游客数', value: '12,856', trend: 15.4 },
  { title: '景点预约量', value: '2,345', trend: 8.4 },
  { title: '活动参与度', value: '89%', trend: 12.7 },
  { title: '设施使用率', value: '92%', trend: -2.4 }
])

// 游客流量趋势数据
const weekDays = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])
const enterData = ref([820, 932, 901, 934, 1290, 1330, 1520])
const goOutData = ref([820, 932, 901, 934, 1290, 1330, 1520])
const passData = ref([820, 932, 901, 934, 1290, 1330, 1520])
const visitorTrendData = ref([])
const dateChange = ref('');

// 游客来源数据
const visitorSourceData = ref([
  { value: 45, name: '周边城市' },
  { value: 30, name: '本地游客' },
  { value: 25, name: '外省游客' }
])

// 游客来源详情
const visitorSourceDetails = ref([
  { 
    title: '周边城市游客',
    count: '5,785',
    percent: 45,
    trend: 12.5,
    color: '#4C87F3'
  },
  {
    title: '本地游客',
    count: '3,857',
    percent: 30,
    trend: 8.3,
    color: '#8BD8FC'
  },
  {
    title: '外省游客',
    count: '3,214',
    percent: 25,
    trend: 15.7,
    color: '#93F1B4'
  }
])

// 格式化数字
const formatNumber = (value: number) => {
  return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
const getFormattedDate = () => {
    const today = new Date(); // 获取当前日期
    const year = today.getFullYear(); // 获取年份
    const month = String(today.getMonth() + 1).padStart(2, '0'); // 获取月份，注意要加1，并补零
    const day = String(today.getDate()).padStart(2, '0'); // 获取日期，并补零

    // 格式化为 YYYYMMDD
    return `${year}${month}${day}`;
}
// 监听窗口大小变化
onMounted(() => {
  dateChange.value = getFormattedDate()
  window.addEventListener('resize', handleResize)
  getActivityList()
  getFeedbackList()
  getHourNumOnTypeByDate()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})


const handleResize = () => {
  nextTick(() => {
    const chartElements = document.querySelectorAll('.ring-chart')
    chartElements.forEach((element) => {
      const chart = echarts.getInstanceByDom(element as HTMLElement)
      chart?.resize()
    })
  })
}

interface ActivityListItem {
  title: string
  status: string
  time: string
  class: string
  icon: string
}

interface FeedbackListItem {
  title: string
  status: string
  time: string
  class: string
  icon: string
}

// 活动列表数据
const activityList = ref<ActivityListItem[]>([])

// 反馈列表数据
const feedbackList = ref<FeedbackListItem[]>([])

// 获取活动列表
const getActivityList = async () => {
  try {
    const res = await scenicActivityPageActivityUsingPost({
      body: {
        current: 1,
        size: 5
      }
    })
    if (res.code === 0 && res.data?.list) {
      activityList.value = res.data.list.map(item => ({
        title: item.activityName || '',
        status: getActivityStatus(item.activityStatus || 0),
        time: item.startTime ? useDateFormat(item.startTime, 'YYYY-MM-DD').value : '',
        class: getActivityStatusClass(item.activityStatus || 0),
        icon: '&#xe6da;'
      }))
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
  }
}

// 获取反馈列表
const getFeedbackList = async () => {
  try {
    const res = await scenicComplaintFeedbackGetComplaintFeedbackUsingPost({
      body: {
        current: 1,
        size: 5
      }
    })
    if (res.code === 0 && res.data?.list) {
      feedbackList.value = res.data.list.map(item => ({
        title: item.content || '',
        status: getFeedbackStatus(item.state || 0),
        time: item.createTime ? useDateFormat(item.createTime, 'YYYY-MM-DD HH:mm').value : '',
        class: getFeedbackStatusClass(item.state || 0),
        icon: '&#xe6df;'
      }))
    }
  } catch (error) {
    console.error('获取反馈列表失败:', error)
  }
}

// 活动状态转换
const getActivityStatus = (status: number) => {
  switch (status) {
    case 1:
      return '未开始'
    case 2:
      return '进行中'
    case 3:
      return '已结束'
    default:
      return '未知'
  }
}

// 活动状态样式
const getActivityStatusClass = (status: number) => {
  switch (status) {
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'info'
    default:
      return 'secondary'
  }
}

// 反馈状态转换
const getFeedbackStatus = (state: number) => {
  switch (state) {
    case 1:
      return '待处理'
    case 2:
      return '处理中'
    case 3:
      return '已回复'
    default:
      return '已关闭'
  }
}

// 反馈状态样式
const getFeedbackStatusClass = (state: number) => {
  switch (state) {
    case 1:
      return 'warning'
    case 2:
      return 'primary'
    case 3:
      return 'success'
    default:
      return 'info'
  }
}

// 查看更多处理函数
const handleMoreActivity = () => {
  router.push('/activity/list')
}

const handleMoreFeedback = () => {
  router.push('/feedback/FeedbackList')
}

// 客流量数据
const getHourNumOnTypeByDate = async () => {
  try {
    const res = await passengerFlowStatisticsHourNumOnTypeByDateUsingPost({
      params:{
        date:dateChange.value
      }
    })
    if(res.code == 0 && res.data){
      weekDays.value = []
      enterData.value = []
      goOutData.value = []
      visitorTrendData.value = []
      res.data.forEach(val=>{
        weekDays.value.push(val.hour)
        enterData.value.push(val.enter)
        goOutData.value.push(val.goOut)
      })
      if(res.data.length >0){
        visitorTrendData.value.push(enterData.value,goOutData.value,)
      }else{
        visitorTrendData.value = []
      }
    }
  } catch (error) {
    console.error('获取客流量数据失败:', error)
  }

}
</script>

<style lang="scss" scoped>
.dashboard-console {
  padding: 16px;

  .statistics-card {
    margin-bottom: 16px;
    background-color: var(--art-main-bg-color);
    border-radius: var(--custom-radius);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    .art-card {
      padding: 20px;
      background-color: var(--art-main-bg-color);
      border-radius: var(--custom-radius);

      .card-content {
        .card-title {
          font-size: 14px;
          color: var(--art-gray-500);
          margin-bottom: 8px;
        }

        .card-value {
          font-size: 24px;
          font-weight: 600;
          color: var(--art-gray-900);
          margin-bottom: 16px;
        }

        .card-footer {
          display: flex;
          align-items: center;
          gap: 8px;

          .trend {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 14px;

            &.up {
              color: #67c23a;
            }

            &.down {
              color: #f56c6c;
            }
          }

          .compared {
            font-size: 12px;
            color: var(--art-gray-500);
          }
        }
      }
    }
  }

  .chart-row {
    margin-bottom: 16px;

    .art-card {
      height: 360px;
      padding: 20px;
      background-color: var(--art-main-bg-color);
      border-radius: var(--custom-radius);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

      .card-header {
        margin-bottom: 20px;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: var(--el-text-color-primary);
        }
      }

      .chart-content {
        height: calc(100% - 40px);
      }

      .visitor-overview {
        display: flex;
        height: 100%;
        // gap: 20px;

        .chart-section {
          flex: 2;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: var(--el-bg-color-overlay);
          border-radius: 8px;
          height: 100%;

          :deep(.ring-chart) {
            width: 100%;
            height: 100% !important;
          }
        }

        .data-section {
          flex: 1;
          padding-right: 20px;
          padding-left: 5px;
          background-color: var(--el-bg-color-overlay);
          border-radius: 8px;

          .source-list {
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            gap: 24px;

            .source-item {
              .source-info {
                .title-row {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin-bottom: 8px;

                  .source-title {
                    display: flex;
                    align-items: center;
                    gap: 8px;

                    .dot {
                      width: 8px;
                      height: 8px;
                      border-radius: 50%;
                    }

                    .title {
                      font-size: 14px;
                      color: var(--el-text-color-regular);
                    }
                  }

                  .count {
                    font-size: 15px;
                    font-weight: 500;
                    color: var(--el-text-color-primary);
                  }
                }

                :deep(.el-progress-bar) {
                  margin-bottom: 8px;
                }

                .trend-info {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  
                  .percent {
                    font-size: 13px;
                    color: var(--el-text-color-secondary);
                  }

                  .trend {
                    font-size: 13px;
                    color: var(--el-color-danger);

                    &.positive {
                      color: var(--el-color-success);
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  .list-row {
    margin-bottom: 0;
  }
}
</style>
